Imports MIMS.WRS.Business
Imports MIMS.WRS.Entities
Imports System.Data
Imports System.Data.Common

Public Class BulkOrderList
    Inherits System.Web.UI.Page

    Protected currentStockClear As Integer = 1
    Protected currentStockFact As Integer = 1
    Protected WithEvents lblSorting As System.Web.UI.WebControls.Label
    Protected WithEvents btnTick As System.Web.UI.WebControls.ImageButton
    Protected WithEvents btnUnTick As System.Web.UI.WebControls.ImageButton
    Protected WithEvents btnArchived As System.Web.UI.WebControls.ImageButton
    Protected WithEvents btnUnArchived As System.Web.UI.WebControls.ImageButton
    Protected txtConPoint As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected currentOrder As Integer = 1

    Public Const SELECTED_SUPPLIER_COOKIE_NAME As String = "SelectedSupplier"

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents rptList As System.Web.UI.WebControls.Repeater
    Protected WithEvents ltrHeader As System.Web.UI.WebControls.Literal
    Protected WithEvents form1 As System.Web.UI.HtmlControls.HtmlForm
    Protected WithEvents btnDelete As System.Web.UI.WebControls.ImageButton
    Protected WithEvents ltrSupplierName As System.Web.UI.WebControls.Literal
    Protected WithEvents btnMarkCompleted As System.Web.UI.WebControls.ImageButton

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Protected Function GetModifiedClass(ByVal container As Object) As String
        Dim modifiedDate As DateTime = DateTime.MinValue

        If Not (DataBinder.Eval(container, "DataItem.ModifiedDate") Is DBNull.Value) Then
            modifiedDate = CType(DataBinder.Eval(container, "DataItem.ModifiedDate"), DateTime)
        End If

        Dim currentDate As DateTime = DateTime.Now
        ' Trim time components
        modifiedDate = New Date(modifiedDate.Year, modifiedDate.Month, modifiedDate.Day)
        currentDate = New Date(currentDate.Year, currentDate.Month, currentDate.Day)

        Dim thisMonday As Date

        If currentDate.DayOfWeek = DayOfWeek.Sunday Then
            thisMonday = currentDate.AddDays(-6)
        Else
            thisMonday = currentDate.AddDays(System.DayOfWeek.Monday - currentDate.DayOfWeek)
        End If

        If modifiedDate.Subtract(thisMonday).TotalDays >= 0 Then
            ' current week
            Return "ThisWeek"
        ElseIf modifiedDate.Subtract(thisMonday).TotalDays >= -7 Then
            ' last week
            Return "LastWeek"
        End If
    End Function

    Protected Function GetRowClass(ByVal container As Object) As String
        Dim ri As RepeaterItem = CType(container, RepeaterItem)
        Dim type As Integer = CType(DataBinder.Eval(container, "DataItem.Type"), Integer)

        Dim className As String

        Select Case type
            Case EBOType.Ordered
                If currentOrder = 1 Then
                    currentOrder = 0
                    className = "OrderItemRow"
                Else
                    currentOrder = 1
                    className = "OrderAlternateItemRow"
                End If
            Case EBOType.StockClear
                If currentStockClear = 1 Then
                    currentStockClear = 0
                    className = "StockClearItemRow"
                Else
                    currentStockClear = 1
                    className = "StockClearAlternateItemRow"
                End If
            Case EBOType.StockFact
                If currentStockFact = 1 Then
                    currentStockFact = 0
                    className = "StockFactItemRow"
                Else
                    currentStockFact = 1
                    className = "StockFactAlternateItemRow"
                End If
        End Select

        Return className
    End Function

    Protected Function GetLGDCatText(ByVal data As Object) As String
        If (data Is DBNull.Value OrElse Convert.ToBoolean(data) = False) Then
            Return "N"
        Else
            Return "Y"
        End If
    End Function

    Protected Function GetUnitsNotStartedHTML(ByVal Container As Object) As String
        Dim data As Object = DataBinder.Eval(Container, "DataItem.TotalQtyNotStarted")
        Dim estimatedDate As Object = DataBinder.Eval(Container, "DataItem.EstimatedDate")

        If (data Is DBNull.Value) Then
            Return "&nbsp;"
        Else
            Dim color As String = "green"

            If (estimatedDate Is DBNull.Value) Then
            Else
                Dim convertedDate As DateTime = Convert.ToDateTime(estimatedDate)
                Dim noOfDays As Integer = convertedDate.Subtract(DateTime.Now).Days
                If (noOfDays > 28) Then
                    color = "green"
                ElseIf (noOfDays >= 14 And noOfDays <= 28) Then
                    color = "#f58500"
                Else
                    color = "red"
                End If
            End If

            Return String.Format("<span style='color: {1}'>{0}</span>", Convert.ToInt32(data), color)
        End If
    End Function

    Protected Function GetEstimatedDateHTML(ByVal Container As Object) As String
        Dim estimatedDate As Object = DataBinder.Eval(Container, "DataItem.EstimatedDate")
        Dim orderDate As DateTime = Convert.ToDateTime(DataBinder.Eval(Container, "DataItem.OrderDate"))
        Dim type As Integer = Convert.ToInt32(DataBinder.Eval(Container, "DataItem.Type"))

        If type = Convert.ToInt32(EBOType.Ordered) AndAlso estimatedDate Is DBNull.Value AndAlso DateTime.Now.Subtract(orderDate).Days > 3 Then
            Return String.Format("<span>&nbsp;</span>")
        Else
            Return GetDateText(estimatedDate)
        End If
    End Function

    Protected Function GetCompletedDateHTML(ByVal Container As Object) As String
        Dim orderedUnitsText As String = GetOrderedText(Container)
        Dim totalQtyCompletedText As String = GetNormalText(DataBinder.Eval(Container, "DataItem.TotalQtyCompleted"))
        Dim totalQtyShippedText As String = GetNormalText(DataBinder.Eval(Container, "DataItem.QuantityShipped"))
        Dim completedDate As Object = DataBinder.Eval(Container, "DataItem.CompletedDate")

        If orderedUnitsText <> "&nbsp;" AndAlso totalQtyCompletedText <> "&nbsp;" AndAlso totalQtyShippedText <> "&nbsp;" _
                AndAlso Convert.ToInt32(orderedUnitsText) = Convert.ToInt32(totalQtyCompletedText) _
                AndAlso Convert.ToInt32(totalQtyCompletedText) = Convert.ToInt32(totalQtyShippedText) Then

            Return String.Format("<span>{0}</span>", GetDateText(completedDate))
        Else
            Return GetDateText(completedDate)
        End If
    End Function

    Protected Function GetNumericText(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return Convert.ToInt32(data).ToString(Config.NumericFormat)
        End If
    End Function

    Protected Function GetDecimalTextForUnitWeight(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return Convert.ToDecimal(data).ToString(Config.DecimalFormatEx)
        End If
    End Function

    Protected Function GetDateText(ByVal data As Object) As String
        If data Is DBNull.Value OrElse Convert.ToDateTime(data).Equals(Nulls.NullDate) Then
            Return "&nbsp;"
        Else
            Return Convert.ToDateTime(data).ToString(Config.DateFormat)
        End If
    End Function

    Protected Function GetPackTypeTextNotNull(ByVal data As Object, ByVal pack As Object) As String
        If data Is DBNull.Value OrElse Convert.ToString(data).Trim() = "" Then
            Return "&nbsp;"
        Else
            Return GetPackTypeText(pack)
        End If
    End Function

    Protected Function GetNormalText(ByVal data As Object) As String
        If data Is DBNull.Value OrElse Convert.ToString(data).Trim() = "" Then
            Return "&nbsp;"
        Else
            Return Server.HtmlEncode(Convert.ToString(data))
        End If
    End Function

    Protected Function GetDecimalText(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return Convert.ToDecimal(data).ToString(Config.DecimalFormat)
        End If
    End Function

    Protected Function GetDecimalTextEx4(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return Convert.ToDecimal(data).ToString(Config.DecimalFormat4)
        End If
    End Function

    Protected Function GetTypeText(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return Utilities.GetBOTypeMeaning(CType(data, EBOType))
        End If
    End Function

    Protected Function GetPackTypeText(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return BulkOrder.GetBOPackTypeMeaning(Convert.ToString(data))
        End If
    End Function

    Protected Function GetPackType2Text(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return BulkOrder.GetBOPackType2Meaning(Convert.ToString(data))
        End If
    End Function

    Protected Function GetOwnerText(ByVal data As Object) As String
        Dim officeID As Integer = Convert.ToInt32(data)
        Try
            Return OfficeService.GetOffice(officeID).OfficeName
        Catch ex As Exception
            Return "[error]"
        End Try
    End Function

    Protected Function GetNegativeNoText(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Dim qty As Integer = Convert.ToInt32(data)
            If (qty < 0) Then
                Return String.Format("<font color='red'>{0}</font>", qty)
            Else
                Return Server.HtmlEncode(Convert.ToString(data))
            End If
        End If
    End Function

    'Protected Function GetCompletedText(ByVal container As Object) As String
    '    Dim data As Object = DataBinder.Eval(container, "DataItem.TotalQtyCompleted")
    '    If data Is DBNull.Value Then
    '        Return "&nbsp;"
    '    Else
    '        Return Convert.ToString(data)
    '    End If

    '    'Dim ri As RepeaterItem = CType(container, RepeaterItem)
    '    'Dim type As Integer = CType(DataBinder.Eval(container, "DataItem.Type"), Integer)
    '    'If type = 1 Then
    '    '    Dim data As Object = DataBinder.Eval(container, "DataItem.TotalQtyCompleted")
    '    '    If data Is DBNull.Value Then
    '    '        Return "&nbsp;"
    '    '    Else
    '    '        Return Convert.ToString(data)
    '    '    End If
    '    'Else
    '    '    Dim data As Object = DataBinder.Eval(container, "DataItem.TotalQtyOrdered")
    '    '    If data Is DBNull.Value Then
    '    '        Return "&nbsp;"
    '    '    Else
    '    '        Return Convert.ToString(data)
    '    '    End If
    '    'End If

    'End Function

    Protected Function GetOrderedText(ByVal container As Object) As String
        Dim ri As RepeaterItem = CType(container, RepeaterItem)
        Dim type As Integer = CType(DataBinder.Eval(container, "DataItem.Type"), Integer)

        If type = EBOType.Ordered Then
            Dim data As Object = DataBinder.Eval(container, "DataItem.TotalQtyOrdered")
            If data Is DBNull.Value Then
                Return "&nbsp;"
            Else
                Return Convert.ToString(data)
            End If
        Else
            Return "&nbsp;"
        End If

    End Function

    Protected Function GetOperaQtyText(ByVal container As Object) As String
        Dim ri As RepeaterItem = CType(container, RepeaterItem)
        Dim type As Integer = CType(DataBinder.Eval(container, "DataItem.Type"), Integer)

        If type = EBOType.Ordered Then
            Dim data As Object = DataBinder.Eval(container, "DataItem.OperaQty")
            If data Is DBNull.Value Then
                Return "&nbsp;"
            Else
                Dim qty As Integer = Convert.ToInt32(data)
                If (qty < 0) Then
                    Return String.Format("<font color='red'>{0}</font>", qty)
                Else
                    Return Server.HtmlEncode(Convert.ToString(data))
                End If
            End If
        Else
            Return "&nbsp;"
        End If
    End Function

    Protected Function GetQtyAvailHTML(ByVal data As Object, ByVal container As Object) As String
        Dim ri As RepeaterItem = CType(container, RepeaterItem)
        Dim id As Integer = Convert.ToInt32(DataBinder.Eval(container, "DataItem.BulkOrderID"))
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return String.Format("<a href=""javascript:;"" onclick=""openDialog('{1}', '{1},', 1)"" title=""go to Deliveried Order List"">{0}</a>", GetNegativeNoText(data), id)
        End If
    End Function

    Protected Function GetQtyAvailCatalogHTML(ByVal container As Object) As String
        Dim qtyAvail As Object = DataBinder.Eval(container, "DataItem.QuantityAvailable")
        Dim packQty As Object = DataBinder.Eval(container, "DataItem.PackQty")
        Try
            If qtyAvail Is DBNull.Value OrElse packQty Is DBNull.Value Then
                Return "&nbsp;"
            Else
                Return BulkOrder.GetQuantityAvailableCatalog(Convert.ToInt32(qtyAvail), Convert.ToInt32(packQty)).ToString()
            End If
        Catch ex As Exception
            Return "&nspb;"
        End Try

    End Function

    Protected Function GetQtyAvailMUKTHGCatalogPackHTML(ByVal container As Object) As String
        Dim qtyAvail As Object = DataBinder.Eval(container, "DataItem.QuantityAvailable")
        Dim packQty As Object = DataBinder.Eval(container, "DataItem.MUKTHGCatPackQty")
        Try
            If qtyAvail Is DBNull.Value OrElse packQty Is DBNull.Value Then
                Return "&nbsp;"
            Else
                Return BulkOrder.CalcQtyAvailMUKTHGCatalogPack(Convert.ToInt32(qtyAvail), Convert.ToInt32(packQty)).ToString()
            End If
        Catch ex As Exception
            Return "&nspb;"
        End Try

    End Function

    Protected Function GetTargetHTML(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            If CType(data, Boolean) = True Then
                Return "<img src=""../images/checkmark.gif"">"
            Else
                Return "&nbsp;"
            End If
        End If
    End Function

    Protected Function GetNaUSAHTML(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            If CType(data, Boolean) = True Then
                Return "&nbsp;"
            Else
                Return "<img src=""../images/checkmark.gif"">"
            End If
        End If
    End Function

    Protected Function GetHomeDeliveredHTML(ByVal Container As Object) As String
        'Dim boTerritories As BulkOrderTerritoryCollection = BulkOrderTerritoryService.GetBulkOrderTerritoriesByBulkOrder(bulkOrderID)
        'Return String.Format("<a href=""javascript:;"" onclick=""openTerritoryDialog('{1}')"" title=""go to view HD Prices and Currency"">{0}</a>", boTerritories.Count, bulkOrderID)

        Dim territoryID As Object = DataBinder.Eval(Container, "DataItem.TerritoryID")
        If (territoryID Is DBNull.Value OrElse Convert.ToInt32(territoryID).Equals(Nulls.NullInteger)) Then
            territoryID = 0
        End If

        Dim productCode As Object = DataBinder.Eval(Container, "DataItem.ProductCode")
        If (productCode Is DBNull.Value OrElse Convert.ToString(productCode) = "") Then
            productCode = ""
        End If

        Dim iCount As Integer = 0
        Dim hdTerritoriesPrices As hdTerritoriesPrices
        If (Convert.ToInt32(territoryID) <> 0 AndAlso Convert.ToString(productCode) <> "") Then
            hdTerritoriesPrices = BulkOrderTerritoryService.GetHDTerritoriesPricesByProductCodeAndTerritoryID(Convert.ToString(productCode), Convert.ToInt32(territoryID))
            If (Not hdTerritoriesPrices Is Nothing) Then
                iCount = 1
            End If
        End If
        Return String.Format("<a href=""javascript:;"" onclick=""openTerritoryDialog('{1}','{2}')"" title=""go to view HD Prices and Currency"">{0}</a>", iCount, territoryID, productCode)
    End Function

    Protected Function GetHarmzedCodeHTML(ByVal Container As Object) As String
        Dim harmzedCode As Object = DataBinder.Eval(Container, "DataItem.HCC_Code")
        If (harmzedCode Is DBNull.Value OrElse Convert.ToString(harmzedCode) = "") Then
            Return "&nbsp;"
        Else
            Return Convert.ToString(harmzedCode)
        End If
    End Function

    Protected Function GetBulkOrderListUrl(ByVal type As Integer) As String
        Return ResolveUrl(UrlBuilder.GetBOListUrl(RequestContext.SupplierCode, type))
    End Function

    Protected ReadOnly Property CurrentScrollPos() As Int32
        Get
            Try
                Return CType(Request.QueryString("pos"), Int32)
            Catch ex As Exception
                Return 0
            End Try
        End Get
    End Property

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Security.DenyIDSUser()

        Dim cookie As HttpCookie = Request.Cookies(SELECTED_SUPPLIER_COOKIE_NAME)

        If cookie Is Nothing Then
            cookie = New HttpCookie(SELECTED_SUPPLIER_COOKIE_NAME)
        End If
        cookie.Value = RequestContext.SupplierCode
        cookie.Expires = DateTime.Now.AddYears(35)
        Response.Cookies.Add(cookie)

        Me.ltrHeader.Text = RequestContext.OfficeName + " Bulk Orders"
        If (RequestContext.CurrentUser.IS_ADMIN = False) Then
            btnDelete.Visible = False
        Else
            Me.btnDelete.Attributes("onclick") = "return deleteClick();"
        End If

        If (RequestContext.BulkOrderType = 0) Then
            btnMarkCompleted.Visible = True
            Me.btnMarkCompleted.Attributes("onclick") = "return markCompletedClick();"
        Else
            btnMarkCompleted.Visible = False
        End If

        Me.btnTick.Attributes("onclick") = "return tickClick();"
        Me.btnUnTick.Attributes("onclick") = "return unTickClick();"

        If (RequestContext.BulkOrderType = 2) Then
            btnArchived.Visible = False
            btnUnArchived.Visible = True
            Me.btnUnArchived.Attributes("onclick") = "return markUnArchiveClick();"
        Else
            btnArchived.Visible = True
            btnUnArchived.Visible = False
            Me.btnArchived.Attributes("onclick") = "return markArchiveClick();"
        End If

        Select Case RequestContext.BOSortType
            Case EBOSorting.Type
                Me.lblSorting.Text = "Type - Owner - Product Code"
            Case EBOSorting.ProductCode
                Me.lblSorting.Text = "Owner - Product Code"
            Case EBOSorting.Owner
                Me.lblSorting.Text = "Product Code - Owner"
            Case EBOSorting.OwnerBONo
                Me.lblSorting.Text = "Owner - BO No - Product Code"
        End Select

        If Not IsPostBack Then
            'Me.ltrSupplierName.Text = SupplierService.GetSupplier(RequestContext.SupplierCode).SupplierName
            Me.rptList.DataSource = BulkOrderService.GetBulkOrders(RequestContext.SupplierCode, RequestContext.BulkOrderType, RequestContext.BOSortType)
            Me.rptList.DataBind()

            RequestContext.ConPointIDForBODetailSS = RequestContext.ConPointIDForBODetail
            txtConPoint.Value = RequestContext.ConPointIDForBODetailSS.ToString()
        End If


    End Sub


    Private Sub btnMarkCompleted_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnMarkCompleted.Click
        If (Request.Form("chkSelect") <> Nothing) Then
            Dim ids As String() = Request.Form("chkSelect").Split(","c)
            Dim id As String
            For Each id In ids
                Dim obj As BulkOrder = BulkOrderService.GetBulkOrder(Integer.Parse(id))
                obj.CompletedDate = DateTime.Now
                BulkOrderService.UpdateBulkOrder(obj)
            Next
            Response.Redirect(Request.RawUrl)
        End If
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnDelete.Click
        If (Request.Form("chkSelect") <> Nothing) Then
            Dim ids As String() = Request.Form("chkSelect").Split(","c)
            Dim id As String
            For Each id In ids
                BulkOrderService.DeleteBulkOrder(Integer.Parse(id))
            Next
            Response.Redirect(Request.RawUrl)
        End If
    End Sub

    Private Sub btnTick_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnTick.Click
        If (Request.Form("chkSelect") <> Nothing) Then
            Dim ids As String() = Request.Form("chkSelect").Split(","c)
            Dim id As String
            For Each id In ids
                Dim obj As BulkOrder = BulkOrderService.GetBulkOrder(Integer.Parse(id))
                obj.Target = True
                BulkOrderService.UpdateBulkOrder(obj)
            Next
            Response.Redirect(Request.RawUrl)
        End If
    End Sub

    Private Sub btnUnTick_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnUnTick.Click
        If (Request.Form("chkSelect") <> Nothing) Then
            Dim ids As String() = Request.Form("chkSelect").Split(","c)
            Dim id As String
            For Each id In ids
                Dim obj As BulkOrder = BulkOrderService.GetBulkOrder(Integer.Parse(id))
                obj.Target = False
                BulkOrderService.UpdateBulkOrder(obj)
            Next
            Response.Redirect(Request.RawUrl)
        End If
    End Sub

    Private Sub btnArchived_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnArchived.Click
        If (Request.Form("chkSelect") <> Nothing) Then
            Dim ids As String() = Request.Form("chkSelect").Split(","c)
            Dim id As String
            For Each id In ids
                Dim obj As BulkOrder = BulkOrderService.GetBulkOrder(Integer.Parse(id))
                obj.IsArchived = True
                BulkOrderService.UpdateBulkOrder(obj)
            Next
            Response.Redirect(Request.RawUrl)
        End If
    End Sub

    Private Sub btnUnArchived_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnUnArchived.Click
        If (Request.Form("chkSelect") <> Nothing) Then
            Dim ids As String() = Request.Form("chkSelect").Split(","c)
            Dim id As String
            For Each id In ids
                Dim obj As BulkOrder = BulkOrderService.GetBulkOrder(Integer.Parse(id))
                obj.IsArchived = False
                BulkOrderService.UpdateBulkOrder(obj)
            Next
            Response.Redirect(Request.RawUrl)
        End If
    End Sub
End Class
